<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--地址数据-->
      <el-col>
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="地址名称" prop="map_Name">
            <el-input
              v-model="queryParams.map_Name"
              placeholder="请输入地址名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="地址状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:map:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:map:import']"
            >导入</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="mapList" @selection-change="handleSelectionChange">
          <el-table-column label="地址编号" align="center" key="map_Id" prop="map_Id" v-if="columns[0].visible" />
          <el-table-column label="地址名称" align="center" key="map_Name" prop="map_Name" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="门店地址" align="center" key="map_Address" prop="map_Address" v-if="columns[2].visible" :show-overflow-tooltip="true" />
          <el-table-column label="状态" align="center" key="status" v-if="columns[3].visible">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="addTime" v-if="columns[4].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.addTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.map_Id !== 1 && scope.row.map_Id !== 0">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:map:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:map:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改地址配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="地址名称" prop="mapName">
              <el-input v-model="form.mapName" placeholder="请输入地址名称" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="门店地址" prop="mapAddress">
              <map-component :address="form.mapAddress" :lng="form.lng" :lat="form.lat" :addressListBoolean="false" :styleObj="mapStyleObj" @pickPoint="getPointInfo"></map-component>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="覆盖范围" prop="area">
              <map-edit-component :area="form.area" :lng="form.lng" :lat="form.lat" :styleObj="areaStyleObj" @pickArea="getAreaInfo"></map-edit-component>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 地址导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的地址数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MapComponent from "@/components/MapComponent"
import MapEditComponent from "@/components/MapEditComponent"
import { listMapApi } from "@/api/system/map";
import { getUser, delUser, addUser, updateUser, changeUserStatus } from "@/api/system/user";
import { getToken } from "@/utils/auth";
export default {
  name: "mapIndex",
  components: {
    MapComponent,
    MapEditComponent
  },
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 日期范围
      dateRange: [],

      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        CurrentPage: 1,
        PageSize: 10,
        userName: undefined,
        addTime: undefined,
        status: undefined
      },
      // 地址表格数据
      mapList: null,
      // 总条数
      total: 0,
      // 列信息
      columns: [
        { key: 0, label: `地址编号`, visible: true },
        { key: 1, label: `地址名称`, visible: true },
        { key: 2, label: `地址门店`, visible: true },
        { key: 3, label: `状态`, visible: true },
        { key: 4, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "地址名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '地址名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      mapStyleObj: {
        width: '100%',
        height: "300px"
      },
      areaStyleObj: {
        width: '100%',
        height: "300px"
      },
      // 地址导入参数
      upload: {
        // 是否显示弹出层（地址导入）
        open: false,
        // 弹出层标题（地址导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的地址数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
    }
  },
  created() {
    this.getList();
  },
  mounted() {

  },
  methods: {
    /** 查询地址列表 */
    getList() {
      this.loading = true;
      listMapApi(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        let { item1 } = response.data;
        if (item1 && item1.length > 0) {
          this.mapList = item1.map(item => ({
            ...item,
            "user_Address": '福州市鼓楼区',
            lng: 119.30692,
            lat: 26.078093,
          }));
          this.total = response.total || item1.length;
        } else {
          this.mapList = response.data;
          this.total = response.total || response.data.length;
        }

        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.user_Id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 表单重置
    reset() {
      this.form = {
        user_Id: undefined,
        userName: undefined,
        userAddress: undefined,
        area: [],
        status: "0",
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加地址";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const user_Id = row.user_Id || this.ids;
      getUser(user_Id).then(response => {
        // this.form = response.data;
        this.form = {
          user_Id: row.user_Id,
          userName: row.user_Name,
          userAddress: row.user_Address,
          area: row.user_area,
          lng: row.lng,
          lat: row.lat,
          status: row.status
        };
        this.open = true;
        this.title = "修改地址";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.user_Id != undefined) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "地址导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    getPointInfo(info) {
      console.log(info);
      this.$set(this.form, 'userAddress', info.address)
      this.$set(this.form, 'lng', info.lng)
      this.$set(this.form, 'lat', info.lat)
    },
    getAreaInfo(info) {
      console.log(info, "getAreaInfo");
      this.$set(this.form, 'area', info.area)
    },
  }
}
</script>